package com.woniu.car.Util;

import com.woniu.car.domain.TProductCategory;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class GetAllCategory  {




    public static List<TProductCategory> listWithTree(List<TProductCategory> entities) {
        // 1.查询出所有的分类

        // 2.组装成父子的树形结构

        List<TProductCategory> level1Menus = new ArrayList<>();
        // 找到所有的一级分类
        for (TProductCategory entity : entities) {
            if (entity.getParentId() == 0) {
                level1Menus.add(entity);
            }
        }

        for (TProductCategory level1Menu : level1Menus) {
            level1Menu.setChildren(getChildrens(level1Menu, entities));
        }
        //排序
        level1Menus.sort(new Comparator<TProductCategory>() {
            @Override
            public int compare(TProductCategory o1, TProductCategory o2) {
                return (o1.getCategoryLevel() == null ? 0 : o1.getCategoryLevel()) - (o2.getCategoryLevel() == null ? 0 : o2.getCategoryLevel());
            }
        });
        return level1Menus;
    }

    /**
     * 递归查找所有的下级分类
     * 在这一级别的分类中找下级分类
     *
     * @param root 当前级别的分类
     * @param all  全部分类
     * @return 下一级分类
     */
    public static List<TProductCategory> getChildrens(TProductCategory root, List<TProductCategory> all) {
        List<TProductCategory> children = new ArrayList<>();
        for (TProductCategory a : all) {
            if (a.getParentId().equals(root.getCategoryId())) {
                a.setChildren(getChildrens(a, all));
                children.add(a);
            }
        }
        children.sort(new Comparator<TProductCategory>() {
            @Override
            public int compare(TProductCategory o1, TProductCategory o2) {
                return (o1.getCategoryLevel() == null ? 0 : o1.getCategoryLevel()) - (o2.getCategoryLevel() == null ? 0 : o2.getCategoryLevel());
            }
        });
        return children;
    }
}
